//
//  YZMIdentifyVerifyViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/4/6.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMIdentifyVerifyViewController.h"
#import "UIViewController+Utils.h"
#import "YZMHintInputView.h"
#import "YZMAppHelper.h"
#import "YZClient.h"
#import "NSString+Utils.h"
#import "YZMAlertView.h"
#import <BlocksKit/UIControl+BlocksKit.h>
#import <BlocksKit/UITextField+BlocksKit.h>

@interface YZMIdentifyVerifyViewController()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) YZMHintInputView *nameInputView;
@property (nonatomic, strong) YZMHintInputView *idCardInputView;
@property (nonatomic, strong) UIButton *submitBT;

@end

@implementation YZMIdentifyVerifyViewController

- (void)viewDidLoad{
    
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    self.title = @"实名认证";
    [self createObjects];
    [self registerForKeyboardAutoWithBottomView:_bottomView];
}

#pragma mark -- network 

- (void)submitToIdentify{
    
    if (![YZMUserService sharedService].networkRequstValid) {
        
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showMessageManual:@"认证中..."];
    
    [YZClient at_updateRealName:self.nameInputView.textField.text andIDCard:self.idCardInputView.textField.text success:^(NSURLResponse *response, id responseObject) {
        
        [hud hide:YES];
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            YZMUserServiceInstance.user.detail.isNamed = YES;
            [MBProgressHUD showMessage:@"身份证认证成功"];
            [[YZMUserService sharedService] fetchUserDetailInfo];
            [YZMHCMInstance popViewController:nil animated:YES];
        }
        else
        {
            if ([topModel.resultMessage isEqualToString:@"您身份认证不通过，请联系客服帮您解决认证问题"]) {
                [[YZMUserService sharedService] fetchUserDetailInfo];
                YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:topModel.resultMessage];
                alertView.cancelButton.hidden = NO;
                [alertView.sureButton setTitle:@"联系客服" forState:UIControlStateNormal];
                alertView.cancleHandle = ^{
                  
                    [YZMHCMInstance popViewController:nil animated:YES];
                };
                alertView.confirmHandle = ^{
                    
                    NSURL *telUrl = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", [YZMAppHelper fetchPhoneNumber]]];
                    if (![[UIApplication sharedApplication] canOpenURL: telUrl]) {
                        
                        [MBProgressHUD showMessage: @"该设备无电话功能"];
                        [YZMHCMInstance popViewController:nil animated:YES];
                        return YES;
                    }
                    
                    [[UIApplication sharedApplication] openURL: telUrl];
                    [YZMHCMInstance popViewController:nil animated:YES];
                    return YES;
                };
                
                [alertView showInView:self.navigationController.view];
                
            }else{
                
                [topModel showMessage];
            }
        }
    } failure:^(NSError *error) {
        
        [hud hide:YES];
        [error yz_showMessage];
    }];
}

#pragma mark -- logic

- (void)refreshSubmitButton{
    
    if (self.nameInputView.textField.text.length <= 0 || self.idCardInputView.textField.text.length <= 0) {
        self.submitBT.layer.borderWidth=1.0;
        self.submitBT.enabled = NO;
        return;
    }
    
    self.submitBT.layer.borderWidth=0.0;
    self.submitBT.enabled = YES;
}

#pragma mark -- ui

- (void)createObjects{
    
    __weak __typeof(&*self) weakSelf = self;
    _bottomView = [UIView new];
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.right.bottom.equalTo(self.view);
        maker.height.mas_equalTo(0);
    }];
    
    UIScrollView *bgSV = [UIScrollView new];
    bgSV.backgroundColor = [UIColor clearColor];
    bgSV.bounces = NO;
    bgSV.showsVerticalScrollIndicator = NO;
    [self.view addSubview:bgSV];
    [bgSV mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.top.right.equalTo(self.view);
        maker.bottom.equalTo(_bottomView.mas_top);
    }];
    
    UIView *containerView = [UIView new];
    containerView.backgroundColor = [UIColor clearColor];
    [bgSV addSubview:containerView];
    [containerView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.edges.equalTo(bgSV);
        maker.width.equalTo(bgSV);
    }];
    
    self.nameInputView = [YZMHintInputView new];
    self.nameInputView.inputLabel.text = @"真实姓名";
    self.nameInputView.textField.placeholder = @"请输入真实姓名";
    
    self.nameInputView.lineTopView.hidden=NO;
    
    [containerView addSubview:self.nameInputView];
    [self.nameInputView.textField addTarget: self action: @selector(refreshSubmitButton) forControlEvents: UIControlEventEditingChanged];
    [self.nameInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(containerView).offset(20);
        make.left.right.equalTo(containerView);
        make.height.mas_equalTo(44);
    }];
    
    self.idCardInputView = [YZMHintInputView new];
    self.idCardInputView.inputLabel.text = @"身份证号";
    self.idCardInputView.textField.placeholder = @"请输入身份证号";
    
    self.idCardInputView.lineBottomView.hidden=NO;
    
    [containerView addSubview:self.idCardInputView];
    [self.idCardInputView.textField addTarget: self action: @selector(refreshSubmitButton) forControlEvents: UIControlEventEditingChanged];
    [self.idCardInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(containerView);
        make.top.equalTo(self.nameInputView.mas_bottom).offset(-1);
        make.height.mas_equalTo(44);
    }];
    
    [self.idCardInputView updateLineIndentationMethod:self.idCardInputView.lineTopView enumeration:LINE_INDENT_SCENE_LEFT indentValue:15];
    
    self.submitBT = [YZMAppStyle NewsubmitButton];
    [self.submitBT setTitle:@"认证" forState:UIControlStateNormal];
    [self.submitBT bk_addEventHandler:^(id sender) {
        
        [weakSelf.view endEditing:YES];
        
        NSString *tmp = self.nameInputView.textField.text;
        
        if (!tmp || [tmp trimSpace].length == 0) {
            
            [MBProgressHUD showMessage:@"姓名不可为空"];
            return;
        }
        
        tmp = self.idCardInputView.textField.text;
        
        if (!tmp || [tmp trimSpace].length == 0) {
            
            [MBProgressHUD showMessage:@"身份证不可为空"];
            return;
        }
        
        if (![tmp yz_isValidIDCardString]) {
            
            [MBProgressHUD showMessage:@"身份证格式错误"];
            return;
        }
        
        [weakSelf submitToIdentify];
        
    } forControlEvents:UIControlEventTouchUpInside];
    [containerView addSubview:self.submitBT];
    [self.submitBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.idCardInputView.mas_bottom).offset(30);
        make.left.equalTo(containerView).offset(15);
        make.right.equalTo(containerView).offset(-15);
    }];
    
    UIButton *button = [self serviceButton];
    [containerView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.submitBT.mas_bottom).offset(12);
        make.height.mas_equalTo(29);
        make.left.equalTo(containerView).offset(44);
        make.right.equalTo(containerView).offset(-44);
    }];
    
    [containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(button).offset(20);
    }];
    
}

- (UIButton *)serviceButton{
    
    UIButton *button = [UIButton new];
    NSString *foreString = @"为保证资金安全，请务必输入您的真实信息。如遇到问题，请联系";
    NSString *lastString = @"客服";
    button.titleLabel.numberOfLines = 0;
    button.titleLabel.font = [YZMAppStyle smallSizeFont];
    button.titleLabel.textColor = [YZMAppStyle colorForGrayText];
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:[foreString stringByAppendingString:lastString]];
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:3];
    paragraphStyle.alignment = NSTextAlignmentCenter;
    [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attrStr.length)];
    
    [attrStr addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForBlueText] range:NSMakeRange(foreString.length, lastString.length)];

    [button setAttributedTitle:attrStr forState:UIControlStateNormal];
    [button bk_addEventHandler:^(id sender) {
        
        [YZMAppHelper callServicePhone];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}


@end
